﻿using PokemonBattle.BattleRoom.Server;
using PokemonBattle.RoomServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace PBO.RoomService
{
    public static class RoomHelper
    {
        #region Varibles

        public static RoomServer _server;
        private static bool _exit;
        private static int UserCount = 0;
        const int USER_MAX = 50;

        #endregion

        public static bool RunServer()
        {
            var setting = new RoomBattleSetting();
            setting.MoveInterval = 200;

            _server = new RoomServer(setting);
            _server.OnAddUserInfo += _server_OnAddUser;
            _server.OnRemoveUserInfo += _server_OnRemoveUser;
            _server.OnUpdateUserInfo += _server_OnUpdateUserInfo;
            _server.OnVerifyUser += _server_OnVerifyUser;
            _server.OnGetMessage += _server_OnGetMessage;

            if (_server.Initialize())
            {
                _server.RunThread();
                //RoomCodeHelper.SetCallback(_server.BroadcastMessage, SendMessage);
                //_server.OnRoomCommand += RoomCodeHelper.ParseMessage;
                return true;
            }
            else
            {
                _server.Dispose();
                _server = null;
                return false;
                //MessageBox.Show("服务器初始化失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //_exit = true;
                //Close();
            }
        }

        static void _server_OnAddUser(User userInfo)
        {
            //if (!string.IsNullOrWhiteSpace(MySetting.WelcomeMessage)) _server.SendMessage(userInfo.Identity, MySetting.WelcomeMessage);
            UserCount++;
        }

        static void _server_OnRemoveUser(int identity)
        {
            UserCount--;
        }

        static void _server_OnUpdateUserInfo(User userInfo)
        {

        }

        static bool _server_OnVerifyUser(User userInfo, out string failMessage)
        {
            failMessage = string.Empty;

            if (UserCount >= USER_MAX)
            {
                failMessage = "房间人数已满";
                return false;
            }

            if (_server.ExistsUser(t => t.Name == userInfo.Name))
            {
                failMessage = "该用户名已被使用";
                return false;
            }

            //if (!RoomCodeHelper.VerifyUser(userInfo.Name, userInfo.Address, ref failMessage))
            //{
            //    return false;
            //}

            return true;
        }

        static void _server_OnGetMessage(string message)
        {
            //AppendText(message);
        }
    }
}
